<?php

namespace App\Common\WX;


use App\Common\Log;
use App\Common\Sys;
use App\Common\User\WxUser;
use App\Common\WX\Api\OfficialAccount;
use App\Model\t_s_accsuper_config;
use App\Model\t_wx_user;
use App\X\EHelper;
use XWX\Common\H;
use XWX\Common\XEntity;

class Wx extends _Base
{
    /**
     * @return t_s_accsuper_config
     */
    public function funcGet_entity()
    {
        return parent::funcGet_entity();
    }


    /**
     * @return OfficialAccount
     * @throws \Exception
     */
    public function getOfficialAccount()
    {
        $app = OfficialAccount::funcIns($this->funcGet_entity());

        return $app;
    }


    /**
     * 获取授权链接
     *
     * @param string $word
     * @param int $scope_int 0：隐式授权，1：显示授权
     * @param string $oauth_root
     *
     * @return string
     */
    function funcGetOAuthUrl($word, $scope_int = 0, $oauth_root = ''): string
    {
        if (H::funcStrIsNullOrEmpty($oauth_root))
        {
//            $oauth_root = $this->funcGet_entity()->aconfig_oauth_root;
            $oauth_root = Sys::funcAppOauthRoot();
        }


        $url = "{$oauth_root}wx/oauth_re?x={$this->funcGet_entity()->aconfig_id}&word=" . urlencode($word);

        if ($scope_int == 1)
        {
            //显式
            $url .= '&scope=snsapi_userinfo';
        }
        else
        {
            //隐式
//            $url .= '&scope=snsapi_base';
        }


        return $url;
    }


    /**
     * 获取openid
     *
     * @param $code
     * @param $get_userinfo
     * @return \XWX\Common\XReturn
     * @throws \Exception
     */
    function funcOAuthOpenid($code, $get_userinfo = false)
    {
        //获取access_token
        $offcial_account = $this->getOfficialAccount();
        $r = $offcial_account->funcGetOauthAccessToken($code);
        if ($r->err())
        {
            return $r;
        }


        $openid = $r->getData('openid');
        $access_token = $r->getData('access_token');

        $entity_wxuser = new t_wx_user();
        $entity_wxuser->wxuser_openid = $openid;
        $entity_wxuser->funcSetX($this->funcGetX());

        if ($get_userinfo)
        {
            Log::funcLogDebug(__METHOD__, '获取用户详细信息');

            $r = $offcial_account->funcGetOauthUserInfo($access_token, $openid);
            if ($r->ok())
            {
                $user_data = $r->getData();
                foreach ($user_data as $k => $v)
                {
                    $entity_wxuser->setVal(t_wx_user::prefix() . $k, $v);
                }
            }
        }


        //延迟插入mysql，先记录redis，性能更快
        $key = WxUser::redisKeyUser($entity_wxuser->wxuser_openid);
        $this->redis()->setEx($key, 60, H::funcToStr($entity_wxuser));

        EHelper::funcGo(function () use ($entity_wxuser)
        {
            $this->funcSetX($entity_wxuser->funcGetX());

            $this->funcUserUpdateMysql($entity_wxuser);
        });

        return $r;
    }

    /**
     * 同步mysql
     *
     * @param $user_data
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    function funcUserUpdateMysql(t_wx_user $user_data)
    {
        $openid = $user_data->wxuser_openid;


        $entity_wxuser = t_wx_user::funcGetWxuser($openid, false);
        if ($entity_wxuser == null)
        {
            $entity_wxuser = new t_wx_user();
            $entity_wxuser->fill($user_data->toArray(XEntity::FILTER_NOT_NULL));
            $entity_wxuser->wxuser_user_data_update_date = H::now();
            $entity_wxuser->funcInsert();
        }
        else
        {
            if ($entity_wxuser->wxuser_user_data_update_date->diffInMinutes(H::now()) > 10)
            {
                $entity_wxuser->fill($user_data->toArray(XEntity::FILTER_NOT_NULL), true);
                $entity_wxuser->wxuser_user_data_update_date = H::now();
                $entity_wxuser->funcUpdate();
            }
            else
            {
                Log::funcLog(__METHOD__, '10分钟内，不再更新');
            }
        }
    }
}